package com.apexsoft.assets.base.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * redis 分布式锁
 */
@Component
public class RedisLockUtil {

    /**
     * 锁的前缀
     */
    private static final String LOCK_PREFIX = "LOCK_";
    /**
     * 锁的超时时长,默认3分钟
     */
    private static final long REDIS_LOCK_TIME = 1000*60*3;
    /**
     * 数据存放在redis的最长时长
     */
    private static final long DATA_LIFE_TIME = 60*60;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * redis 分布式锁，默认锁3分钟
     * @param key key
     * @return
     */
    public boolean lock(String key){
        return lock(key,REDIS_LOCK_TIME);
    }

    /**
     * redis 分布式锁
     * @param key key
     * @param lockTime 锁的时长(ms)
     * @return
     */
    public boolean lock(String key,long lockTime){
        String lock = LOCK_PREFIX + key;
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            long expireAt = System.currentTimeMillis() + lockTime + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
            if(acquire){
                return true;
            }else {
                byte[] value = connection.get(lock.getBytes());
                if (Objects.nonNull(value) && value.length > 0) {
                    long expireTime = Long.parseLong(new String(value));
                    // 如果锁已经过期
                    if (expireTime < System.currentTimeMillis()) {
                        // 重新加锁，防止死锁
                        byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + lockTime + 1).getBytes());
                        return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
                    }
                }
            }
            return false;
        });
    }

    /**
     * 删除锁
     *
     * @param key
     */
    public void deleteLock(String key) {
        String lock = LOCK_PREFIX + key;
        redisTemplate.delete(lock);
    }

    /**
     *  存放数据到redis
     * @param key
     * @param value
     * @param dataLifeTime 数据保存的最长时长(秒)
     * @return
     */
    public boolean put(String key,String value,long dataLifeTime){
        redisTemplate.execute((RedisCallback) connection -> {
            Boolean acquire = connection.setNX(key.getBytes(), value.getBytes());
            if(acquire){
                connection.expire(key.getBytes(),dataLifeTime);
            }
            return acquire;
        });
        return false;
    }
    /**
     *  存放数据到redis,默认存放 1小时
     * @param key
     * @param value
     * @return
     */
    public boolean put(String key,String value){
        return put(key, value,DATA_LIFE_TIME);
    }
    /**
     * 删除数据
     *
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }
}
